package com.inspinia.config.rpc;

import com.ctrip.framework.apollo.Config;
import com.ctrip.framework.apollo.ConfigChangeListener;
import com.ctrip.framework.apollo.ConfigFile;
import com.ctrip.framework.apollo.ConfigService;
import com.ctrip.framework.apollo.core.enums.ConfigFileFormat;
import com.inspinia.config.rpc.api.ApolloConfigCallback;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class ApolloConfigImpl implements ApolloConfigCallback {

    ConfigChangeListener configChangeListener;

    public ApolloConfigImpl(){
        if (configChangeListener == null){
            configChangeListener = ApolloConfigChangeListener.configChangeListener();
        }
    }

    @Override
    public Config getConfigByNamespace(String key) {
        Config config = ConfigService.getConfig(key);
        //已经去重
        config.addChangeListener(configChangeListener);
        return config;
    }

    @Override
    public Config getDefaultConfig() {
        Config appConfig = ConfigService.getAppConfig();
        appConfig.addChangeListener(configChangeListener);
        return appConfig;
    }


    @Override
    public ConfigFile getConfigByPropNameAndFormat(String key, ConfigFileFormat fileFormat) {
        return ConfigService.getConfigFile(key,fileFormat);
    }
}
